package com.bigfreakindeals.Activities;

import java.io.IOException;

import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import twitter4j.TwitterException;

import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Controller.TwitterHelper;
import com.bigfreakindeals.Models.Company;
import com.bigfreakindeals.Protocols.SoapHandlers.FAQHandler;

import com.bigfreakindeals.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.Theme;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author abhinava_srivastava
 */

public class TwitterActivity extends Activity implements OnClickListener {

	/**
	 * Twitter instance object
	 */

	private WebView webView = null;
	private Context context;
	private Handler handleEvent = null;
	private String authURL;
	TwitterHelper helper;
	String tweetMessage;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.twitterpage);
		handleEvent = new Handler();
		
		tweetMessage = getIntent().getStringExtra(Constant.TAG_TWITTER_MESSAGE);
		
		System.out.println("PostMessage"+tweetMessage);
		
		context = this;
		
		helper = new TwitterHelper();
		 
		webView = (WebView)findViewById(R.id.twitterscreen);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new WebViewClient());
		
		
		WebViewClient webViewClientExt = new WebViewClientExt();
		webView.setWebViewClient(webViewClientExt);
		webView.setVerticalScrollbarOverlay(true);
		webView.setFocusableInTouchMode(true);
		webView.setFocusable(true);
		webView.requestFocus(View.FOCUS_DOWN);
		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
		webSettings.setDomStorageEnabled(true);
		webSettings.setSaveFormData(false);
		webSettings.setSavePassword(false);
		webSettings.setLoadsImagesAutomatically(true);
		webSettings.setBlockNetworkImage(false);
		
		Button  continuetwitter = (Button)findViewById(R.id.continuetwitter);
		continuetwitter.setOnClickListener(this);
		
		continuetwitter.setBackgroundDrawable(Tools.getDrawableButtonGeneric(new int[]{0xffffffff, 0xffd0d0d0}, 10));
	 	
		((ProgressBar) findViewById(R.id.progress)).setVisibility(View.VISIBLE);
		String header = "Share on Twitter";
	
		((TextView)findViewById(R.id.header_title)).setText(header);
		
		webView.setVisibility(View.INVISIBLE);
		
	}

	
	private void setCredentials(){
		
		new Thread() {
			public void run() {
				try {
					sleep(5);
				} catch (Exception e) {
				}
				
				try {
					System.out.println("TwitterActivity - step5");
					
					authURL = helper.accessTwitter();
					
				}catch (TwitterException e) {
					System.out.println("ex6"+authURL);
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("AUTH URL"+authURL);
				if (authURL != null)
					webView.loadUrl(authURL);
				else
					displayErrorMessage();
			}

		}.start();
		
	}
	private void displayErrorMessage(){
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
		setCredentials();
	}


	public void getAccessToken(String pincode) throws Exception{
	
	helper.sendTweet(pincode, tweetMessage);
	
	alertOK(this.getParent(),"Tweeted the deal successfully", "OK");
	
	}

	public void alertOK(Context context, String message, String button){
	
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(message)
		       .setCancelable(false)
		       .setPositiveButton(button, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               dialog.dismiss();
		               onBackPressed();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
		
	}
	
	/**
	 * Pin code dialog Requests the user to enter pin shown on twitter
	 */
	public void twitterPinCodeDialog() {
		LinearLayout pinHolder = new LinearLayout(this);
		pinHolder.setGravity(Gravity.CENTER);
		final EditText editPinCode = new EditText(this);
		editPinCode.setGravity(Gravity.CENTER);
		editPinCode.setHint("Pin Code");
		editPinCode.setWidth(200);
		pinHolder.addView(editPinCode);

		Builder pinBuilder = new AlertDialog.Builder(this.getParent());
		pinBuilder.setView(pinHolder).setTitle("Twitter Pin Code Entry").setMessage("Please enter displayed twitter code into the field")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (editPinCode.getText().toString() != null && !editPinCode.getText().toString().equals("")) {
								
									try {	
										hideVirtualKeyboard();
										dialog.dismiss();
										
										((ProgressBar) findViewById(R.id.progress)).setVisibility(View.VISIBLE);
										
										getAccessToken(editPinCode.getText().toString());
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
										
						
						} else {
							Toast.makeText(context, "Pin code is required", Toast.LENGTH_SHORT).show();
							dialog.dismiss();
							twitterPinCodeDialog();
						}

					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Toast.makeText(context, "To share your news please complete login next time", Toast.LENGTH_LONG).show();
						dialog.dismiss();
					}
				}).show();
	}
	public void hideVirtualKeyboard() {
		try {
			InputMethodManager inputManager = (InputMethodManager) TwitterActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.hideSoftInputFromInputMethod(TwitterActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
	
		} catch (Exception e) {
			
		}
	}
	public class WebViewClientExt extends WebViewClient {
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			((ProgressBar) findViewById(R.id.progress)).setVisibility(View.INVISIBLE);
			webView.setVisibility(View.VISIBLE);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
		
		return false;
		}

		@Override
		public void onPageFinished(WebView view, String url) {

		}

	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		twitterPinCodeDialog();
		
	}
}
